package org.openkoala.koala.deploy.action;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.openkoala.koala.console.ConsoleFactory;
import org.openkoala.koala.deploy.webservice.pojo.WebServiceDeploy;
import org.openkoala.koala.deploy.webservice.util.WebServiceDeployCreate;
import org.openkoala.koala.exception.KoalaException;
import org.openkoala.koala.maven.MavenExcuter;
import org.openkoala.koala.popup.BaseAction;
import org.openkoala.koala.util.ProjectQueryUtil;

/**
 * WebService Action的实现
 * 
 * @author lingen
 * 
 */
public abstract class WebServiceDeployAction extends BaseAction {

	private WebServiceDeploy webServiceDeploy;

	private String selectedPath;

	@Override
	public void run(IAction action) {
		analyticsProject();
		openDialog();
	}

	private void analyticsProject() {

		selectedPath = getResource().getLocationURI().getPath();
		try {
			if (ProjectQueryUtil.isParentProject(selectedPath) == false) {
				selectedPath = selectedPath.substring(0,
						selectedPath.lastIndexOf("/"));
			}
		} catch (KoalaException e1) {
			ConsoleFactory.console(e1.getMessage());
			e1.printStackTrace();
		}
		try {
			ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(shell);
			monitorDialog.run(true, true, new IRunnableWithProgress() {
				@Override
				public void run(IProgressMonitor monitor)
						throws InvocationTargetException, InterruptedException {
					ConsoleFactory.showConsole();
					monitor.beginTask("分析中...", 4);
					monitor.worked(1);
					monitor.setTaskName("检查原项目的正确性");
					try {
						MavenExcuter.runMaven(selectedPath);
						monitor.worked(2);
						monitor.setTaskName("分析项目所拥有的接口及实现...");
						webServiceDeploy = WebServiceDeployCreate
								.analytics(selectedPath);
						monitor.done();
					} catch (KoalaException e) {
						e.printStackTrace();
						MessageDialog.openError(shell,
								"ERROR", e.getMessage() + ":" + e.getClass().toString());
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public WebServiceDeploy getWebServiceDeploy() {
		return webServiceDeploy;
	}
	
	public void setWebServiceDeploy(WebServiceDeploy webServiceDeploy) {
		this.webServiceDeploy = webServiceDeploy;
	}

	public abstract void process();

	public abstract void openDialog();

}
